package com.yylany.service;

import com.github.pagehelper.PageHelper;
import com.yylany.bo.PageRequest;
import com.yylany.mapper.TbNewsMapper;
import com.yylany.pojo.TbNews;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * Description: pinyougou
 *
 * @author <a href="mailto:17777502615@163.com">yaoyonglong</a>
 * @date 2018/12/19
 * @since 1.0.0
 */
@Service
@Transactional
public class NewsService {

    private TbNewsMapper newsMapper;

    @Autowired
    public NewsService(TbNewsMapper newsMapper) {
        this.newsMapper = newsMapper;
    }

    /**
     * 获取分页数据的代码
     * private Integer limit;// 限制条数
     * private Integer offset;// 起始索引
     * private Integer page; // 当前页
     * private Integer per_page;// 每页条数
     * private String sort_by; // 排序字段
     * private String sort_way; //排序方式  asc  升序   desc  降序
     *
     * @param pageRequest
     * @return
     */
    public List<TbNews> findNewsByPage(PageRequest pageRequest) {
        PageHelper.startPage(pageRequest.getPage(), pageRequest.getPer_page());
        Example example = new Example(TbNews.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isBlank(pageRequest.getSort_way()) || "desc".equals(pageRequest.getSort_way())) {
            example.setOrderByClause("created_at desc");
        } else {
            example.setOrderByClause("created_at asc");
        }
        List<TbNews> list = newsMapper.selectByExample(example);
        return list;
    }

    /**
     * 获取总记录数的代码
     *
     * @return
     */
    public int findTotalCount() {
        return newsMapper.size();
    }


}
